<template>
  <div style="min-height: calc(100vh - 460px);">
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      labelAlign="right"
      :label-col="{  style: { width: '90px' }}"
      :wrapper-col="{span:12}"
    >
      <a-form-item label="公司名称" name="company">
        <a-input
          v-model:value="formState.company"
          placeholder="请输入公司名称"
        />
      </a-form-item>

      <a-form-item label="所在城市" name="position">
        <a-cascader
          placeholder="请选择城市"
          v-model:value="formState.position"
          :options="areaTree"
          :fieldNames="{ label: 'name', value: 'adcode', children: 'children' }"
        />
      </a-form-item>

      <a-form-item label="详细地址" name="company_address">
        <a-input
          v-model:value="formState.company_address"
          placeholder="请输入详细地址"
        />
      </a-form-item>

      <a-form-item label="公司类型" name="company_type">
        <a-checkbox-group
          v-model:value="formState.company_type"
          name="checkboxgroup"
          :options="dict.company_type"
        />
      </a-form-item>

      <a-form-item label="业务类型" name="company_business">
        <a-checkbox-group
          v-model:value="formState.company_business"
          name="checkboxgroup"
          :options="dict.business_type"
        />
      </a-form-item>

      <a-form-item label="公司职位" name="company_position">
        <a-select
          v-model:value="formState.company_position"
          placeholder="请选择职位"
        >
          <a-select-option
            :key="item.id"
            v-for="item in dict.company_position"
            :value="item.id"
            >{{ item.name }}</a-select-option
          >
        </a-select>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { message } from "ant-design-vue";
import { onMounted, reactive } from "vue";
import {
  company_info_pz,
  company_info_add,
  company_info,
} from "../../../../Api/work";

import area from "./areaCode.json";

const areaTree = ref([]);

const formState = ref({
  company: "",
  position: "",
  province: "",
  city: "",
  area: "",
  company_address: "",
  company_type: "",
  company_business: "",
  company_position: "",
});
const rules = {
  company: [
    {
      required: true,
      message: "请输入",
      trigger: "change",
    },
  ],
  company_type: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  company_business: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
  company_position: [
    {
      required: true,
      message: "请选择",
      trigger: "change",
    },
  ],
};

const dict = reactive({
  company_type: [],
  business_type: [],
  company_position: [],
});
function arrayToTree(array) {
  // 创建一个映射，以便通过id快速访问元素
  const map = {};
  array.forEach((item) => (map[item.adcode] = { ...item, children: [] }));

  // 构建树
  const tree = [];
  array.forEach((item) => {
    const parent = map[item.parent];
    if (parent) {
      // 如果找到了父元素，将当前元素添加到父元素的children数组中
      parent.children.push(map[item.adcode]);
    } else {
      // 如果没有父元素（即顶级元素），将当前元素添加到树中
      tree.push(map[item.adcode]);
    }
  });

  return tree;
}
onMounted(async () => {
  const treeData = arrayToTree(area);
  areaTree.value = treeData?.[0]?.children;

  const res = await company_info_pz();
  const res2 = await company_info();

  let position = res2.data.data?.province?[
      Number(res2.data.data?.province),
      Number(res2.data.data?.city),
      Number(res2.data.data?.area)
    ]:[];

    if(position?.[2]&&position?.[2]==position?.[1]) position = position.slice(0,2)

    formState.value = {
    ...res2.data?.data,
    position,
    company_business: res2.data.data?.company_business?JSON.parse(res2.data.data?.company_business):"",
    company_type: res2.data.data?.company_type?JSON.parse(res2.data.data?.company_type):"",
    company_position:  res2.data.data?.company_position?res2.data.data?.company_position+'':""
  };
  dict.company_type = res.data.data.company_type?.map((p) => {
    return {
      label: p.name,
      value: p.id,
    };
  });
  dict.business_type = res.data.data.business_type?.map((p) => {
    return {
      label: p.name,
      value: p.id,
    };
  });
  dict.company_position = res.data.data.company_position;
});

const formRef = ref(null);

const confirm = async () => {
  formRef.value
    .validate()
    .then(async () => {
      if (formState.value.position?.length > 0) {
        formState.value.province = formState.value.position[0];
        formState.value.city = formState.value.position[1];
        formState.value.area =
          formState.value.position?.[2] || formState.value.position[1];
      }
      const res = await company_info_add(formState.value);
      console.log("res", res);
      if (res?.data?.code == 1) {
        message.success("操作成功");
      } else {
        message.error(res?.data?.msg);
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
};

const cancel = () => {
  formRef.value.resetFields();
};

defineExpose({
  confirm,
  cancel,
});
</script>
